package com.shushan.receiver;

import android.app.KeyguardManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.OnePiexlActivity;
import com.shushan.db.ChildBeanDao;
import com.shushan.home.TabHomeActivity;
import com.shushan.lockscreen.EyeSleepFloatWindow;
import com.shushan.lockscreen.EyeSleepWindowManager;
import com.shushan.lockscreen.FreeWarnWindowManager;
import com.shushan.lockscreen.GamesWindowManager;
import com.shushan.lockscreen.LockScreenWindowManager;
import com.shushan.lockscreen.SplashWindowManager;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.service.ForegroundRTAService;
import com.shushan.service.LockOutRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.HomeSwitchActivity;
import com.shushan.ui.CountdownTextView;
import com.shushan.ui.PopupDialog;
import com.shushan.util.OpenSettingUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;

import java.util.List;

/**
 * @ClassName: ScreenBroadcastReceiver
 * @Desciption: screen状态广播接收者
 * @author: yichaohua
 * @date: 2018-05-25
 */
public class ScreenBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "ScreenBroadcastReceiver";


    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null) {
            return;
        }

        String strAction = intent.getAction();

        //清掉系统锁屏（还有其他方式）
//        KeyguardManager keyguardManager = (KeyguardManager) context
//                .getSystemService(Context.KEYGUARD_SERVICE);
//        KeyguardManager.KeyguardLock keyguardLock = keyguardManager
//                .newKeyguardLock(context.getPackageName());
//        keyguardLock.disableKeyguard();

        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if (Intent.ACTION_SCREEN_OFF.equals(strAction)) {
            //屏幕灭
            Log.i(TAG, "屏幕灭：ACTION_SCREEN_OFF触发");

            if(isChildControl){
                //启动1像素Activity
                Intent intent3 = new Intent(context,OnePiexlActivity.class);
                intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent3);
            }

            getUserinfo(context);

            boolean isForeRtaAlive = SystemUtils.isServiceWork(context, Constants.FOREGROUND_RTA_SERVICE_CLASS_NAME);
            boolean isDialRtaAlive = SystemUtils.isServiceWork(context, Constants.DIAL_RTA_SERVICE_CLASS_NAME);
            if(isChildControl && !(isForeRtaAlive || isDialRtaAlive)){
                SplashWindowManager.createEyeFloatWindow(context);

                Intent intent1 = new Intent(context,LockOutRTAService.class);
                context.stopService(intent1);
            }

            boolean isEyeSleepAvailable = EyeSleepWindowManager.isIsEyeSleepAvailable();
            boolean isEyeOpen = SharedPreferencesUtils.getBooleanDate(Constants.PROJECT_EYE_SWITCH_SHAREPREFERS_KEY);
            Log.i(TAG,"isEyeSleepAvailable=" + isEyeSleepAvailable + " isEyeOpen=" + isEyeOpen);
            if(isEyeOpen && isEyeSleepAvailable){
                BabyApplication shuShanApplication = BabyApplication.getInstance();
                shuShanApplication.setScreenOffTime(System.currentTimeMillis());
                EyeSleepFloatWindow eyeSleepFloatWindow = EyeSleepWindowManager.getEyeSleepFloatWindow();
                if(eyeSleepFloatWindow != null){
                    CountdownTextView countdownTextView = eyeSleepFloatWindow.getCountdownTextView();
                    if(countdownTextView != null){
                        countdownTextView.stop();
                    }

                }
            }
        }else if (Intent.ACTION_SCREEN_ON.equals(strAction)){
            //屏幕解锁
            Log.i(TAG, "屏幕点亮：ACTION_SCREEN_ON触发");

            if(isChildControl){
                Intent intent4 = new Intent();
                intent4.setAction(Constants.ONE_PIX_FINISH_RECEIVER_ACTION);
                LocalBroadcastManager.getInstance(context).sendBroadcast(intent4);
            }

//            boolean isForeRtaAlive = SystemUtils.isServiceWork(context, Constants.FOREGROUND_RTA_SERVICE_CLASS_NAME);
//            boolean isDialRtaAlive = SystemUtils.isServiceWork(context, Constants.DIAL_RTA_SERVICE_CLASS_NAME);
//            TelephonyManager telMgr = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
//            if(isChildControl && !(isForeRtaAlive || isDialRtaAlive) && (telMgr.getCallState() == TelephonyManager.CALL_STATE_RINGING
//                    || telMgr.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK)){
//                SplashWindowManager.startCount();
//            }

            boolean isEyeSleepAvailable = EyeSleepWindowManager.isIsEyeSleepAvailable();
            boolean isEyeOpen = SharedPreferencesUtils.getBooleanDate(Constants.PROJECT_EYE_SWITCH_SHAREPREFERS_KEY);
            Log.i(TAG,"isEyeSleepAvailable=" + isEyeSleepAvailable + " isEyeOpen=" + isEyeOpen);
            if(isEyeOpen && isEyeSleepAvailable){
                BabyApplication shuShanApplication = BabyApplication.getInstance();
                long screenOffTime = shuShanApplication.getScreenOffTime();
                int difTime = (int) ((System.currentTimeMillis() - screenOffTime)/1000);
                EyeSleepFloatWindow eyeSleepFloatWindow = EyeSleepWindowManager.getEyeSleepFloatWindow();
                if(eyeSleepFloatWindow != null){
                    CountdownTextView countdownTextView = eyeSleepFloatWindow.getCountdownTextView();
                    if(countdownTextView != null){
                        int time = countdownTextView.getTime();
                        Log.i(TAG,"time=" + time + " difTime=" + difTime);
                        countdownTextView.setTimes(time - difTime);
                    }

                }
            }

        } else if (Intent.ACTION_USER_PRESENT.equals(strAction)) {
            //屏幕解锁
            Log.i(TAG, "屏幕解锁：ACTION_USER_PRESENT触发");

            if(isChildControl){
//                SplashWindowManager.startCount();
                SplashWindowManager.removeEyeFloatWindow(context);
                SystemUtils.sendForegActivity(context, TabHomeActivity.class);

                Intent intent1 = new Intent(context,LockOutRTAService.class);
                context.stopService(intent1);
            }

        }
    }

    private void readyClear(Context context) {

        FreeWarnWindowManager.getInstance(context).dismissWarnDialog();
    }

    private void showLockSettingDialog(final Context context) {
        final PopupDialog popupDialog = new PopupDialog(context);
        popupDialog.setMessage("发现系统也设置了锁屏，为了避免解锁两次建议您关闭系统锁屏(在设置中选择 无密码)。");
        popupDialog.setPositiveButton("设置", new PopupDialog.DialogOnClickListener() {
            @Override
            public void onClick(View v) {
                BaseActivity baseActivity = (BaseActivity) ActivityStackManager.getActivityStackManager().currentActivity();
                if(baseActivity != null){
                    baseActivity.setAllowBack(true);
                }else {
                    Log.e(TAG,"baseActivity == null");
                }

//                OpenSettingUtils.gotoSystemLockSetting(context);
            }
        });
        popupDialog.setNegativeButton("取消", new PopupDialog.DialogOnClickListener() {
            @Override
            public void onClick(View v) {
                popupDialog.dismiss();
            }
        });

        FragmentActivity fragmentActivity = (FragmentActivity) context;
        if (!fragmentActivity.isFinishing()) {
            popupDialog.show(fragmentActivity.getWindow().getDecorView(),
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        }
    }

    public void getUserinfo(final Context context) {
        if(context == null){
            Log.e(TAG,"getUserinfo context == null");
            return;
        }
        UrlParse urlParse = new UrlCommParse(context, UrlConst.BASE_URL).appendRegion(UrlConst.GET_USER_INFO);
        urlParse.putValue("phone",SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UserBean>() {


                    @Override
                    protected void onSuccess(UserBean userBean) {
                        if(userBean != null){
                            BabyApplication.getInstance().setUserBean(userBean);

                            List<ChildBean> childList = userBean.getChildList();
                            if(childList.size() > 0){
                                new ChildBeanDao(BabyApplication.getInstance()).dropAndAddList(childList);
                            }
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {

                    }
                });
    }
}
